from flask import Flask, render_template, request, redirect, url_for, send_from_directory, abort
import os
from datetime import datetime

app = Flask(__name__)

# 配置上传文件夹
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 确保上传文件夹存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

@app.route('/')
def index():
    # 列出所有上传的文件
    files = os.listdir(UPLOAD_FOLDER)
    return render_template('index.html', files=files, now=datetime.now())

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # 检查是否有文件部分
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        # 如果用户没有选择文件，浏览器也会提交一个空的part
        if file.filename == '':
            return redirect(request.url)
        # 保存文件
        filename = file.filename
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('index'))
    return render_template('upload.html', now=datetime.now())

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    # 允许局域网内其他设备访问
    clear_screen()
    print("---------------------------------------------------------------------")
    print("---------------------------------------------------------------------")
    print("---------------------------------------------------------------------") 
    print("------文件共享服务已启动，其他通局域网设备可以通过以上IP端口访问-----")
    print("---------------------------------------------------------------------")
    print("---------------------------------------------------------------------")
    print("---------------------------------------------------------------------") 
    print("                       CopyRight@:Venus                              ")
    print("---------------------------------------------------------------------")
    print("---------------------------------------------------------------------") 
    app.run(host='0.0.0.0', port=80)